import 'package:appflutterhomeschool/api/api_service.dart';
import 'package:appflutterhomeschool/api/dio_utils.dart';
import 'package:appflutterhomeschool/model/answers_model.dart';
import 'package:appflutterhomeschool/model/notification_model.dart';
import 'package:appflutterhomeschool/model/questions_model.dart';
import 'package:appflutterhomeschool/route/application.dart';
import 'package:appflutterhomeschool/route/routes.dart';
import 'package:appflutterhomeschool/utils/sp_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:logger/logger.dart';
import 'package:provider/provider.dart';

import '../my_app_view_model.dart';

class NoticeltemDialogViewModel extends ChangeNotifier {
  BuildContext me;

  //点击事件
  TapGestureRecognizer gestureOnTap1 = TapGestureRecognizer();
  TapGestureRecognizer gestureOnTap2 = TapGestureRecognizer();

  NoticeltemDialogViewModel(this.me, this.notification1);

  NotificationModel notification, notification1;
  List<QuestionsModel> listQuestions = [];

  MyAppViewModel myAppViewModel;
  bool identity = SpUtil.getString("role_now") == "TEACHER";

  initView() {
    if (notification1?.id != null) {
      //填写点击事件
      gestureOnTap1.onTap = () {
        Application().navigatePushToPage(
            me, Routes.statusSelectionListPage, {"pageTag": 1});
      };
      //未读点击事件
      gestureOnTap2.onTap = () {
        Application().navigatePushToPage(
            me, Routes.statusSelectionListPage, {"pageTag": 0});
      };
      myAppViewModel = Provider.of<MyAppViewModel>(me);
      identity = myAppViewModel.identity;
      Dio2Utils.getInstance().post(
          ApiService.parentNotificationIsRead,
          {
            "notification_record_id": notification1?.id,
            //类型：String  必有字段  备注：通知记录id
            "student_id": myAppViewModel?.studentInformationModel?.subjectId
            //类型：String  必有字段  备注：学生id
          },
          (successCallBack) {},
          (errorCallBack) {});
      print("========identity=========$identity");
      if (!identity) {
        if (notification1.notificationType == "Task") {
          Logger().d("进来了");
          Dio2Utils.getInstance()
              .get("${ApiService.taskRecords20}${notification1.id}/", {},
                  (successCallBack) {
            if (successCallBack["data"] == null ||
                successCallBack["data"] == []) {
              return;
            }
            List data = successCallBack["data"];
            if (data.length == 0) {
              Navigator.pop(me);
              return;
            }
            Logger().d(successCallBack["data"]);
            notification = NotificationModel.fromJson(data.first);
            notifyListeners();
          }, (errorCallBack) {});
        } else if (notification1.notificationType == "Form") {
          //TODO 家长 表单
          //表单
          Dio2Utils.getInstance().post(ApiService.parentGetNotificationDetail, {
            "notification_id": notification1.id,
            //类型：String  必有字段  备注：通知id
            "student_id": myAppViewModel.studentInformationModel.subjectId
            //类型：String  必有字段  备注：学生id
          }, (successCallBack) {
            if (successCallBack["data"] == null ||
                successCallBack["data"] == []) {
              return;
            }
            var data = successCallBack["data"];
            if (data == null) {
              return;
            }
            var notificationData = data["notification_data"];

            if (notificationData == null) {
              return;
            }
            var notificationMap = notificationData["notification"];

            if (notificationMap == null) {
              return;
            }
            notification = NotificationModel.fromJson(notificationMap);
            listQuestions = notification.listQuestions;
            notifyListeners();
          }, (errorCallBack) {});
        } else if (notification1.notificationType == "Notification") {
          Dio2Utils.getInstance()
              .get("${ApiService.notificationRecords15}${notification1.id}/", {},
                  (successCallBack) {
            if (successCallBack["data"] == null ||
                successCallBack["data"] == []) {
              return;
            }
            List data = successCallBack["data"];
            if (data.length == 0) {
              Navigator.pop(me);
              return;
            }
            notification = NotificationModel.fromJson(data.first);
            notifyListeners();
          }, (errorCallBack) {});
        }
      } else {
        notification = notification1;
        //类型：String  必有字段  备注：通知类型（表单：Form,任务：Task，通知：Notification，讨论:ChatRoom）
        if (notification.notificationType == "Task") {
//          tasks26
          Dio2Utils.getInstance()
              .get("${ApiService.tasks26}${notification1.id}/", {},
                  (successCallBack) {
            if (successCallBack["data"] == null ||
                successCallBack["data"] == []) {
              return;
            }
            List data = successCallBack["data"];
            if (data.length == 0) {
              Navigator.pop(me);
              return;
            }
            print("=============1=========");
            notification = NotificationModel.fromJson(data.first);
            print("=============2=========");
            listQuestions = notification.listQuestions;
            print("==============3========");
            notifyListeners();
          }, (errorCallBack) {});
        }
      }
    }
  }

  //家长端确认按钮触发
  sureReedOnTap() {
    Dio2Utils.getInstance().post(ApiService.parentNotificationIsConfirmed, {
      "notification_record_id": notification.id,
      //类型：String  必有字段  备注：通知记录
      "student_id": myAppViewModel.studentInformationModel.subjectId
      //类型：String  必有字段  备注：学生id
    }, (successCallBack) {
      Navigator.pop(me);
    }, (errorCallBack) {});
  }

  //单选选项
  radiClick(int index, int optionIndex) {
    List<Options> optionList = listQuestions[index].options;
    for (int i = 0; i < optionList.length; i++) {
      listQuestions[index].options[i].select = optionIndex == i;
    }
    notifyListeners();
  }

  //多选选项
  multipleChoice(int index, int optionIndex) {
    List<Options> optionList = listQuestions[index].options;
    listQuestions[index].options[optionIndex].select =
        !optionList[optionIndex].select;
    notifyListeners();
  }

  //提交表单
  desposeFormAnswerOnTap() {
    List<AnswersModel> listAnswers = [];

    for (int i = 0; i < listQuestions.length; i++) {
      List<Answer> answerList = [];
      QuestionsModel questionsModel = listQuestions[i];
      if (questionsModel.questionType == "C") {
        if (questionsModel.questionText.text != "") {
          answerList
              .add(Answer(answerContent: questionsModel.questionText.text));
        }
      } else {
        List<Options> optionsList = questionsModel?.options ?? [];
        for (int j = 0; j < optionsList?.length; j++) {
          if (optionsList[j].select) {
            answerList.add(Answer(
                order: optionsList[j].order, option: optionsList[j].option));
          }
        }
      }
      listAnswers.add(AnswersModel(
          questionOrder: listQuestions[i].questionOrder, answer: answerList));
    }

    Map<String, dynamic> map = {
      "notification_id": notification.id,
      //类型：String  必有字段  备注：通知id
      "student_id": myAppViewModel.studentInformationModel.subjectId,
      //类型：String  必有字段  备注：学生id
      "answers": listAnswers
    };

    Logger().d(map);
    Dio2Utils.getInstance().post(ApiService.desposeFormAnswer, map,
        (successCallBack) {
      Navigator.pop(me);
    }, (errorCallBack) {});
  }
}
